package cn.itcast.web.controller;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class LoginController extends BaseController{

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    /**
     * 用户登录
     * @param email
     * @param password
     * @return
     */
    @RequestMapping(value = "/login",name = "登录")
    public String login(String email,String password){

//        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password)){
//            return "forward:/login.jsp";
//        }
//
//        User loginUser = userService.findByEmail(email);
//
//        if (loginUser != null && loginUser.getPassword().equals(password)){
//            session.setAttribute("loginUser",loginUser);
//            List<Module> modules = moduleService.findModuleByUserId(loginUser.getId());
//            session.setAttribute("modules",modules);
//
//            return "home/main";
//        }else {
//            request.setAttribute("error","用户名或者密码错误");
//            return "forward:/login.jsp";
//        }

        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken upToken = new UsernamePasswordToken(email,password);
            subject.login(upToken);
            User user = (User) subject.getPrincipal();
            session.setAttribute("loginUser",user);
            List<Module> modules = moduleService.findModuleByUserId(user.getId());
            session.setAttribute("modules",modules);

            return "home/main";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error","用户名或者密码错误");

            return "forward:login.jsp";
        }
    }

    @RequestMapping("/home")
    public String home(){

        return "home/home";
    }

    /**
     * 注销用户
     * @return
     */
    @RequestMapping("/logout")
    public String logout(){

        SecurityUtils.getSubject().logout();
        session.removeAttribute("loginUser");
        session.invalidate();

        return "forward:/login.jsp";
    }
}
